package com.qwer.service.accesscontrol.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.qwer.mapper.accesscontrol.AccApiRepository;
import com.qwer.model.accesscontrol.AccApiInfo;
import com.qwer.service.accesscontrol.AccApiService;

@Service
public class AccApiServiceImpl implements AccApiService{
    
    @Autowired
    private AccApiRepository repository;
    
    

    @Override
    public Page<AccApiInfo> findList(Pageable pageable,AccApiInfo model) {
        
        Specification<AccApiInfo> spec = new Specification<AccApiInfo>() {

            @Override
            public Predicate toPredicate(Root<AccApiInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotEmpty(model.getApiName())) {
                    list.add(cb.like(root.get("apiName"),"%"+model.getApiName()+"%"));
                }
                
                if(null!=model.getUserId()){
                    list.add(cb.equal(root.get("userId"), model.getUserId()));
                }
                
                
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
            
        };   
        Page<AccApiInfo> orderMasterPage = repository.findAll(spec,pageable);
        
        List<AccApiInfo> orderDTOList = orderMasterPage.getContent();

        return new PageImpl<AccApiInfo>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }


    @Override
    public void save(AccApiInfo model) {
         repository.save(model);
    }

    @Override
    public void deleteById(Integer id) {
         repository.delete(id);;
    }


    @Override
    public AccApiInfo findById(Integer id) {
        return repository.findOne(id);
    }


	@Override
	public List<AccApiInfo> findByUserId(Integer userId) {
		return repository.findByUserId(userId);
	}

}
